package com.twb.netty.server;

import java.net.InetSocketAddress;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

@Component
public class NettyServer {
	
	protected static Logger log = LoggerFactory.getLogger(NettyServer.class);

	/**
	 * 端口
	 */
	@Value("${twb.netty.port}")
	private int port;

	/**
	 * 主线程
	 */
	private EventLoopGroup bossGroup;
	
	/**
	 * 工作线程
	 */
	private EventLoopGroup workerGroup;

	/**
	 * 服务器
	 */
	private ServerBootstrap server;

	/**
	 * 回调
	 */
    private ChannelFuture future;
    
    public NettyServer() {
    	bossGroup = new NioEventLoopGroup();
    	workerGroup = new NioEventLoopGroup();
    }
	
	/**
	 * @throws InterruptedException 
	 * @Title start
	 * @Description 启动服务
	 * @author DHL
	 * @date 2021年7月7日 上午8:45:07
	 */
	@PostConstruct
	public void start() throws InterruptedException {
		server = new ServerBootstrap()
				.group(bossGroup, workerGroup)
				.channel(NioServerSocketChannel.class)
				.localAddress(new InetSocketAddress(port))
				// 保持长连接
				.childOption(ChannelOption.SO_KEEPALIVE, true)
				.childHandler(new NettyServerInitializer());
		
		future = server.bind().sync();
		
		if (future.isSuccess()) {
			log.info("==========【NETTY】启动监听：{}", future.channel().localAddress());
		}
	}
	
	/**
	 * @Title destroy
	 * @Description 销毁
	 * @author DHL
	 * @date 2021年7月7日 上午9:01:20
	 */
	@PreDestroy
	public void destroy() {
		bossGroup.shutdownGracefully().syncUninterruptibly();
		workerGroup.shutdownGracefully().syncUninterruptibly();
		log.info("==========【NETTY】关闭成功");
	}

}
